#!/usr/bin/env python3

# 兴盛优选

# import http.client as http_client
# http_client.HTTPConnection.debuglevel = 1
import requests
from tzutil.ob import Ob
from datetime import datetime
import csv
from json import loads
from pprint import pprint
from lnglat import lnglat
from cache import Cache
from hashlib import blake2s

COL = "leader_nickname prov_city_address province_name city_name pickup_name pickup_address".split()

cache = Cache(__file__[:-3])

# def fetch(city, writer):
#     lnglat_li = lnglat(city)
#     length = len(lnglat_li)
#     total = 0

#     for pos, p in enumerate(lnglat_li):
#         cost = pos/length
#         if pos%1000 == 0:
#             print(
#                 str(datetime.now())[:19],
#                 city, length - pos,
#                 "%.2f%%"%(100*cost),
#                 int(total/cost) if cost else 0
#             )

#         url = "https://shopapi.youxianbianli.com/users/leaderinfo?pickup_pid=94938"

#         headers = {
#             'tctoken': "lp02kHG+TLscJCkMGP0ccSdWBv04PlcFoXyoQua0LjndYm33TWbv7gr9rke69HB1AuzrmS294EqBtFlYl6T1qc+tlnhwVGPvauNplc7ZlxfOOsq4pL1J4XPrJ/Zm1L+KbRRKBMe8mYIkPn45/SATRhNt4w36t4eZzTlRYlTN09et0cW+iojAYTP2LJGUwrIT8GTUkmZi94bD"
#         }

#         response = Ob(**requests.get( url, headers=headers, params={"lon":p[0],"lat":p[1]}).json())
#         for i in response.rows:
#             txt = "\n".join(i)
#             print(city,i)
#         # url = f"https://mall-store.xsyxsc.com/mall-store/store/getNearStoreList?mapX={p[0]}&mapY={p[1]}&userKey=8be3d5dd-23e1-4b04-bf12-efca98d69d12"
#         # r = cache.get(url)['data']
#         # rlen = len(r)
#         # same = 0
#         # for i in r:
#         #     if 'storePhoto' in i:
#         #         del i['storePhoto']

#         #     storeId = int(i['storeId'])
#         #     yesterdayOrderQty = i['yesterdayOrderQty']
#         #     print(yesterdayOrderQty,'yesterdayOrderQty')
#         #     if storeId in EXIST:
#         #         same += 1
#         #         print(
#         #             "exist %.2f%%"%(same/rlen)
#         #         )
#         #         continue
#         #     total+=1
#         #     EXIST.add(storeId)

#         #     li = [
#         #         str(i.get(key,'') or '').replace("\r\n",' ').replace('\r',' ').replace('\n',' ') for key in COL
#         #     ]
#         #     writer.writerow([city]+li)


def main():
    # li = lnglat('湖南')
    # print(len(li))
    # return
    # from city import CITY

        # for pos, city in enumerate(CITY,1):
        #     print(f"完成 {pos} 个 · {pos/len(CITY):.2%}")
        #     fetch(city, writer)

    EXIST = set()
    pid = 0
    prepid = 0
    with open(__file__[:-2]+'csv', 'w', encoding='utf-8-sig') as f:
        writer = csv.writer(f)
        writer.writerow(['pid']+COL)
        while 1:
            pid+=1
            url = f"https://shopapi.youxianbianli.com/users/leaderinfo?pickup_pid={pid}"
            headers = {
                'tctoken': "lp02kHG+TLscJCkMGP0ccSdWBv04PlcFoXyoQua0LjndYm33TWbv7gr9rke69HB1AuzrmS294EqBtFlYl6T1qc+tlnhwVGPvauNplc7ZlxfOOsq4pL1J4XPrJ/Zm1L+KbRRKBMe8mYIkPn45/SATRhNt4w36t4eZzTlRYlTN09et0cW+iojAYTP2LJGUwrIT8GTUkmZi94bD"
            }


            response = Ob(**cache.get( url, headers)).rows
            t = []
            for i in COL:
                t.append(response[i].strip(" \r\n"))
            txt="\n".join(t).encode('utf-8')
            key = blake2s(txt).digest()
            if key in EXIST:
                if pid%1000 == 0:
                    print(pid, response)
                if pid-prepid > 100000:
                    break
                continue
            EXIST.add(key)
            prepid = pid
            writer.writerow([pid]+t)
            print(pid, " / ".join(t))


if __name__ == "__main__":
    import single_process.init
    main()

